package com.unidt.www.module.third.doc.utils;

import com.alibaba.fastjson.JSON;
import com.unidt.www.framework.common.util.object.BeanMapUtils;
import com.unidt.www.module.third.doc.domain.ProjectBusInfoDo;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author sk
 * @Description:
 * @Date 2022/11/23 17:38
 **/
public class HtmlDocUtils {


    public static void main(String[] args) throws IOException {

        String path = "d://wordtohtml.html";

        List<TableDto> tables = new ArrayList<>();
        tables.add(new TableDto("项目分年度建设进度计划", "项目分年度建设进度计划", "项目的技术先进性比较优势分析"));
        Map<String, Object> result = new HashMap<>();
        try {
           result = parseHtml(path, 0, tables);
        }catch (Exception e){
            result = parseHtml(path, 0,1, tables);
        }

        Map<String, Object> s = BeanMapUtils.transForObject(result, ProjectBusInfoDo.class);

        ProjectBusInfoDo projectBusInfo = JSON.parseObject(JSON.toJSONString(s), ProjectBusInfoDo.class);

    }


    public static Map<String, Object> parseHtml(String path, Integer tableIndex,Integer endTableIndex, List<TableDto> tableDtos) {
        Map<String, Object> result = new HashMap<>();

        try {
            File file = new File(path);
            Document doc = Jsoup.parse(file, "UTF-8");
            Element body = doc.body();
            for(Integer i = tableIndex;i<=endTableIndex;i++){
                body.getElementsByTag("table");
                Elements es = body.getElementsByTag("table");
                Integer size = es.size();
                if(size>i){
                    Element table = es.get(i);
                    Elements trs = table.getElementsByTag("tr");

                    result.putAll(parseMap(trs));

                    List<TableDto> tables = creatTable(tableDtos, trs);
                    if(!tables.isEmpty() ){
                        for(Integer h=0;h<tables.size();h++){
                            TableDto t = tables.get(h);
                            if(t.getStartRow()>0){
                                TableVo data = parseTable(t, trs);
                                result.put(data.getName(), data.getTableData());
                            }
                        }

                    }
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static Map<String, Object> parseHtml(String path, Integer tableIndex, List<TableDto> tableDtos) {
        Map<String, Object> result = new HashMap<>();

        try {
            File file = new File(path);
            Document doc = Jsoup.parse(file, "UTF-8");
            Element body = doc.body();
            Element table = body.getElementsByTag("table").get(tableIndex);

            Elements trs = table.getElementsByTag("tr");

            result = parseMap(trs);

            List<TableDto> tables = creatTable(tableDtos, trs);
            Map<String, Object> finalResult = result;
            tables.forEach(t -> {
                TableVo data = parseTable(t, trs);
                finalResult.put(data.getName(), data.getTableData());
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static Map<String, Object> parseMap(Elements trs) {
        Map<String, Object> result = new HashMap<>();

        Integer size = trs.size();
        for (Integer i = 0; i < size; i++) {

            Element tr = trs.get(i);

            Elements tds = tr.getElementsByTag("td");

            Integer tdLength = tds.size();
            Integer kk = tdLength % 2;

            for (Integer j = 0; j < tdLength; j++) {
                Element td = tds.get(j);
                String text = td.getElementsByTag("span").text();
                text =getText(text);

                if (kk == 0) {
                    if (j % 2 == 0) {
                        Element vt = tds.get(j + 1);
                        String value = vt.getElementsByTag("span").text();
                        value = getText(value);
                        text =getText(text);

                        result.put(text, value);
                    }
                } else if (tdLength == 1) {
                    String[] values = text.split("：").length < 2 ? text.split(":") : text.split("：");
                    if (values.length >= 2) {
                        result.put(values[0], text);
                    }
                }
            }
        }
        return result;
    }

    public static TableVo parseTable(TableDto tableDto, Elements trs) {

        TableVo tableVo = new TableVo();
        tableVo.setName(tableDto.getTableName());

        List<String> headers = getHeader(trs, tableDto.getStartRow());

        List data = getData(trs, headers, tableDto.getStartRow(), tableDto.getEndRow());
        tableVo.setTableData(data);
        return tableVo;
    }

    public static List<TableDto> creatTable(List<TableDto> tableVos, Elements trs) {
        List<TableDto> tables = new ArrayList<>();
        tableVos.forEach(e -> {

            Integer startRow = 0;
            Integer endRow = 0;

            Integer size = trs.size();
            for (Integer i = 0; i < size; i++) {
                Element tr = trs.get(i);
                Elements tds = tr.getElementsByTag("td");

                Integer tdLength = tds.size();

                for (Integer j = 0; j < tdLength; j++) {
                    Element td = tds.get(j);
                    String text = td.getElementsByTag("span").text();
                    text =getText(text);

                    if (e.getStart().equals(text) || text.contains(e.getStart()) ) {
                        startRow = i;
                    }
                    if (e.getEnd().equals(text) || text.contains(e.getEnd()) ) {
                        endRow = i;
                    }
                }
            }
            e.setStartRow(startRow);
            if(startRow>0 &&endRow==0){
                endRow = startRow +4;
            }
            e.setEndRow(endRow);
            if (endRow > startRow) {
                tables.add(e);
            }

        });
        return tables;
    }

    public static List<String> getHeader(Elements trs, Integer start) {

        Element project_info = trs.get(start);

        Elements items_attr = project_info.getElementsByTag("td");

        List<String> headers = new ArrayList<>();

        for (Integer j = 0; j < items_attr.size(); j++) {
            Element element = items_attr.get(j);
            String text = element.getElementsByTag("span").text();
            text =  getText(text);
            headers.add(text);
        }

        return headers;
    }


    public static List getData(Elements trs, List<String> headers, Integer startRow, Integer endRow) {

        List<Map<String, String>> dataList = new ArrayList<>();

        Boolean isEnd = false;
        for (Integer k = startRow + 1; k < endRow; k++) {
            if (isEnd) {
                break;
            }
            if(k>=trs.size()){
                break;
            }
            Element row = trs.get(k);
            Map<String, String> item = new HashMap<>();

            Elements tds = row.getElementsByTag("td");
            for (Integer s = 0; s < tds.size(); s++) {
                Element t = tds.get(s);

                String text = t.getElementsByTag("span").text();
                text =  getText(text);
                if (s == 0 && (StringUtils.isBlank(text) || text.contains("..."))) {
                    isEnd = true;
                    break;
                }
                item.put(headers.get(s), text);
            }
            if (!isEnd) {
                dataList.add(item);
            }

        }

        return dataList;
    }


    private  static  String getText(String text){

        if(StringUtils.isBlank(text)){
            return  text;
        }
        text = text.replace(" ", "");
        text = text.replace("\n", "");
        text = text.replace("\t", "");
        return  text;
    }
}
